//
//  UpdateHandler.m
//  WeddingStoreFinder
//
//  Created by Macdev on 11/19/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "UpdateHandler.h"
#import "POI.h"
#import "Dress.h"


//update the database if there is an update
#define kUpdateType_Update 10

//just check for update and tell the delegate the result
#define kUpdateType_CheckForUpdate 20

static long long serverLastUpdateTimestamp;

@interface UpdateHandler()

@property int updateType;

@end


@implementation UpdateHandler

@synthesize delegate, updateType, updateResultMessage;

- (void) dealloc {
	[updateResultMessage release];
	[super dealloc];
}

#pragma mark - public methods


- (void) update {
	self.updateType = kUpdateType_Update;
	WebService *ws = [[WebService alloc] init];
	ws.wsType = kWSType_CheckForUpdate;
	ws.delegate = self;
	
	[ws sendRequest];
	[ws release];
	if ([((NSObject*)self.delegate) respondsToSelector:@selector(updateIsInProgress:)]) {
		[self.delegate updateIsInProgress:@"Checking for updates..."];
	}
}

- (void) checkForUpdate {
	self.updateType = kUpdateType_CheckForUpdate;
	WebService *ws = [[WebService alloc] init];
	ws.wsType = kWSType_CheckForUpdate;
	ws.delegate = self;

	[ws sendRequest];
	[ws release];
	if ([((NSObject*)self.delegate) respondsToSelector:@selector(updateIsInProgress:)]) {
		[self.delegate updateIsInProgress:@"Checking for updates..."];
	}
	
}

#pragma mark - WebServiceDelegate

- (void) allWentOK:(WebService *)webService {
	if (self.updateType == kUpdateType_CheckForUpdate) {
		BOOL needUpdate = NO;
		if ([webService.jsonResult objectForKey:kJSON_response]) {
			NSNumber *serverLastUpdateTimestampNumb = [[webService.jsonResult objectForKey:kJSON_response] valueForKey:kJSON_lastUpdateTimestamp];
			long long serverLastUpdateTimestampT = [serverLastUpdateTimestampNumb longLongValue];
			//NSLog(@"regi - új ts: %qi - %qi", [ApplicationConf getLongLongForKey:kAppConfKey_LastUpdateTimeStamp], serverLastUpdateTimestamp);
			if ([AppConf getLongLongForKey:kAppConfKey_LastUpdateTimeStamp] < serverLastUpdateTimestampT) {
				needUpdate = YES;
			}
			
		}
		if ([((NSObject*)self.delegate) respondsToSelector:@selector(needUpdate:)]) {
			[self.delegate needUpdate:needUpdate];
		}
	} else if (self.updateType == kUpdateType_Update) {
		if (webService.wsType == kWSType_CheckForUpdate) {
			//if update need call the poi update service:
			BOOL needUpdate = NO;
			if ([webService.jsonResult objectForKey:kJSON_response]) {
				NSNumber *serverLastUpdateTimestampNumb = [[webService.jsonResult objectForKey:kJSON_response] valueForKey:kJSON_lastUpdateTimestamp];
				serverLastUpdateTimestamp = [serverLastUpdateTimestampNumb longLongValue];
				//NSLog(@"regi - új ts: %qi - %qi", [ApplicationConf getLongLongForKey:kAppConfKey_LastUpdateTimeStamp], serverLastUpdateTimestamp);
				if ([AppConf getLongLongForKey:kAppConfKey_LastUpdateTimeStamp] < serverLastUpdateTimestamp) {
					needUpdate = YES;
				}
				
			}
			if ([((NSObject*)self.delegate) respondsToSelector:@selector(needUpdate:)]) {
				[self.delegate needUpdate:needUpdate];
			}
			if (needUpdate) {
				WebService *ws = [[WebService alloc] init];
				ws.delegate = self;
				ws.wsType = kWSType_UpdatePOI;
				
				[ws sendRequest];
				[ws release];
				if ([((NSObject*)self.delegate) respondsToSelector:@selector(updateIsInProgress:)]) {
					[self.delegate updateIsInProgress:@"Download is in progress"];
				}
			} else {
				self.updateResultMessage = @"Your client is up to date!";
				if ([((NSObject*)self.delegate) respondsToSelector:@selector(updateDone:)]) {
					[self.delegate updateDone:self];
				}
			}
		} else if (webService.wsType == kWSType_UpdatePOI) {
			//save poi-s and call the event update service:
			
			//process poi list:
			[POI processPOIList:webService.jsonResult];
			
			WebService *ws = [[WebService alloc] init];
			ws.delegate = self;
			ws.wsType = kWSType_UpdateDress;
			
			[ws sendRequest];
			[ws release];
	
		} else if (webService.wsType == kWSType_UpdateDress) {
			//process eventlist:
			if ([webService.jsonResult valueForKey:kJSON_response]) {
				[Dress processDressList:webService.jsonResult];
				//save the new lastUpdateDate:
				[AppConf setLongLong:serverLastUpdateTimestamp forKey:kAppConfKey_LastUpdateTimeStamp];
			}

			//refresh ui:
			[[NSNotificationCenter defaultCenter] postNotificationName:kNotification_MapViewController_ReloadMap object:nil];
			[[NSNotificationCenter defaultCenter] postNotificationName:kNotification_PopAllViewControllerToRoot object:nil];
			[[NSNotificationCenter defaultCenter] postNotificationName:kNotification_StoreListviewController_ReloadList object:nil];
			[[NSNotificationCenter defaultCenter] postNotificationName:kNotification_RobeListViewController_ReloadList object:nil];
			
			self.updateResultMessage = @"Update done successfully!";
			if ([((NSObject*)self.delegate) respondsToSelector:@selector(updateDone:)]) {
				[self.delegate updateDone:self];
			}
		}
	}
}

- (void) anErrorOccurred:(WebService *)webService {
	self.updateResultMessage = [webService.wsError localizedDescription];
	[self.delegate anErrorOccurred:self];
}

- (void) networkUnavailable:(WebService *)webService {
	self.updateResultMessage = [webService.wsError localizedDescription];
	[self.delegate anErrorOccurred:self];
}

@end
